﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web;
using System.Xml.Serialization;
using System.Xml;
using Newtonsoft.Json.Linq;
using AutoMapper;
using System.Linq.Expressions;
using System.Reflection;
using System.ServiceModel;
using Framework.Infrastructure.IoC.Unity.LifetimeManagers;
using Framework.DCI;
using Framework.Infrastructure.IoC;
using Microsoft.Practices.Unity;

namespace Framework.Infrastructure
{
    public class QueryParameter
    {
        private string name = null;
        private string value = null;

        public QueryParameter(string name, string value)
        {
            this.name = name;
            this.value = value;
        }

        public string Name
        {
            get { return name; }
        }

        public string Value
        {
            get { return value; }
            set { this.value = value; }
        }
    }

    public class AutoMapForMemberOption<TSource, TDestination>
        where TSource : class
        where TDestination : class
    {
        public AutoMapForMemberOption()
        {

        }
        public AutoMapForMemberOption(Expression<Func<TDestination, object>> destinationMember,
            Action<IMemberConfigurationExpression<TSource>> memberOptions)
        {
            DestinationMember = destinationMember;
            MemberOptions = memberOptions;
        }

        public Expression<Func<TDestination, object>> DestinationMember{get;set;}
        public Action<IMemberConfigurationExpression<TSource>> MemberOptions{get;set;}
    }

    public static class Utility
    {

        public static TRole ActAs<TRole>(this IAggregateRoot entity)
            where TRole : Framework.DCI.IRole
        {
            TRole role = IoCFactory.Resolve<TRole>(new ParameterOverride("actor", entity));
            return role;
        }

        public static TAttribute GetCustomAttribute<TAttribute>(this object obj)
        where TAttribute : Attribute
        {
            if (obj.GetType().IsDefined(typeof(TAttribute), true))
            {
                var attr = Attribute.GetCustomAttribute(obj.GetType(), typeof(TAttribute), true) as TAttribute;
                return attr;
            }
            return null;
        }

        public static IEnumerable<T> ForEach<T>(
                this IEnumerable<T> source,
                Action<T> act)
        {
            foreach (T element in source) act(element);
            return source;
        }

        public static void DisposeContainerExtensions()
        {
            if (OperationContext.Current != null)
            {
                OperationContext.Current.Extensions.OfType<ContainerExtension>().ForEach<ContainerExtension>(
                ce =>
                {
                    var idisposable = ce.Value as IDisposable;
                    if (idisposable != null)
                    {
                        idisposable.Dispose();
                    }

                }
                ); 
            }
        }

        public static TDestination ToMapObject<TDestination>
          (this object src)
            where TDestination : class
        {
            var mapper = Mapper.CreateMap(src.GetType(), typeof(TDestination));
            var dest = Mapper.Map(src, src.GetType(), typeof(TDestination)) as TDestination;
            return dest;
        }

        public static TDestination ToMapObject<TSource, TDestination>
           (this TSource src,
           params AutoMapForMemberOption<TSource, TDestination>[] memberOptions)
            where TSource : class
            where TDestination : class
        {
            return ToMapObject(src, null, null, memberOptions);
        }

        public static TDestination ToMapObject<TSource, TDestination>
           (this TSource src, TDestination dest,
           params AutoMapForMemberOption<TSource, TDestination>[] memberOptions)
            where TSource : class
            where TDestination : class
        {
            return ToMapObject(src, dest, null, memberOptions);
        }

        public static TDestination ToMapObject<TSource, TDestination>
          (this TSource src, TDestination dest,
          params Expression<Func<TDestination, object>>[] ignoreMembers)
            where TSource : class
            where TDestination : class
        {
            return ToMapObject(src, dest, ignoreMembers, null);
        }

        public static TDestination ToMapObject<TSource, TDestination>
            (this TSource src, TDestination dest,
            IEnumerable<Expression<Func<TDestination, object>>> ignoreMembers,
            AutoMapForMemberOption<TSource, TDestination>[] memberOptions)
            where TSource : class
            where TDestination : class
        {
            var mapper = Mapper.CreateMap<TSource, TDestination>();

            if (ignoreMembers != null && ignoreMembers.Count() > 0)
            {
                ignoreMembers.ForEach(ignore => {
                    mapper.ForMember(ignore, opt => opt.Ignore());
                });
            }

            if (memberOptions != null && memberOptions.Length > 0)
            {
                memberOptions.ForEach(mo =>
                {
                    mapper.ForMember(mo.DestinationMember, mo.MemberOptions);
                });
            }
            if (dest == null)
            {
                dest = Mapper.Map<TSource, TDestination>(src) as TDestination;
            }
            else
            {
                dest = Mapper.Map(src, dest) as TDestination;
            }
            return dest;
        }

        //public static object ToMapObject(this object src, object dest)
        //{
        //    Mapper.CreateMap(src.GetType(), dest.GetType());
        //    if (dest == null)
        //    {
        //        dest = Mapper.Map(src, src.GetType(), dest.GetType());
        //    }
        //    else
        //    {
        //        dest = Mapper.Map(src, dest, src.GetType(), dest.GetType());
        //    }
        //    return dest;
        //}

        public static TDestination CreateObject<TSource, TDestination>(TSource obj)
        {
            Mapper.CreateMap<TSource, TDestination>();
            var dest = Mapper.Map<TSource, TDestination>(obj);
            return dest;
        }

        public static void UpdateObject<TSource, TDestination>(TSource obj, TDestination destObj)
        {
            Mapper.CreateMap<TSource, TDestination>();
            Mapper.Map<TSource, TDestination>(obj, destObj);
        }

        public static void UpdateObject(dynamic srcObj, dynamic destObj)
        {
            Mapper.CreateMap(srcObj.GetType(), destObj.GetType());
            Mapper.Map(srcObj, destObj, srcObj.GetType(), destObj.GetType());
        }

        public static string GetTimeToString(DateTime datetime, bool isEnglish)
        {
            string lang = isEnglish ? "en-US" : "zh-CN";
            string timetext = string.Empty;
            TimeSpan span = DateTime.Now - datetime;
            if (span.Days > 30)
            {
                timetext = datetime.ToShortDateString();
            }
            else if (span.Days >= 1)
            {
                timetext = string.Format("{0}{1}", span.Days, GetResource("Day", lang));
            }
            else if (span.Hours >= 1)
            {
                timetext = string.Format("{0}{1}", span.Hours, GetResource("Hour", lang));
            }
            else if (span.Minutes >= 1)
            {
                timetext = string.Format("{0}{1}", span.Minutes, GetResource("Minute", lang));
            }
            else if (span.Seconds >= 1)
            {
                timetext = string.Format("{0}{1}", span.Seconds, GetResource("Second", lang));
            }
            else
            {
                timetext = string.Format("1{0}", GetResource("Second", lang));
            }
            return timetext;
        }

        public static IQueryable<T> GetPageElements<T>(this IQueryable<T> query, int pageIndex, int pageSize) 
        {
            return query.Skip(pageIndex * pageSize).Take(pageSize);
        }
        internal static string GetUniqueIdentifier(int length)
        {
            try
            {
                int maxSize = length;
                char[] chars = new char[62];
                string a;
                a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                chars = a.ToCharArray();
                int size = maxSize;
                byte[] data = new byte[1];
                RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
                crypto.GetNonZeroBytes(data);
                size = maxSize;
                data = new byte[size];
                crypto.GetNonZeroBytes(data);
                StringBuilder result = new StringBuilder(size);
                foreach (byte b in data)
                {
                    result.Append(chars[b % (chars.Length - 1)]);
                }
                // Unique identifiers cannot begin with 0-9
                if (result[0] >= '0' && result[0] <= '9')
                {
                    return GetUniqueIdentifier(length);
                }
                return result.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GENERATE_UID_FAIL", ex);
            }
        }

        public static T GetValueByKey<T>(this object obj, string name)
        {
            T retValue = default(T);
            object objValue = null;
            try
            {
                if (obj is Newtonsoft.Json.Linq.JObject)
                {
                    var jObject = obj as Newtonsoft.Json.Linq.JObject;
                    var property = jObject.Property(name);
                    if (property != null)
                    {
                        var value = property.Value as Newtonsoft.Json.Linq.JValue;
                        if (value != null)
                        {
                            objValue = value.Value;
                        }
                    }
                }
                else
                {
                    var property = obj.GetType().GetProperty(name);
                    if (property != null)
                    {
                        objValue = property.GetValue(obj, null);
                    }
                }

                if (objValue != null)
                {
                    retValue = (T)objValue;
                }
            }
            catch (System.Exception)
            {
                retValue = default(T);
            }
            return retValue;
        }

        public static object GetValueByKey(this object obj, string name)
        {
            object objValue = null;
            if (obj is Newtonsoft.Json.Linq.JObject)
            {
                var jObject = obj as Newtonsoft.Json.Linq.JObject;
                var property = jObject.Property(name);
                if (property != null)
                {
                    var value = property.Value as Newtonsoft.Json.Linq.JValue;
                    if (value != null)
                    {
                        objValue = value.Value;
                    }
                }
            }
            else
            {
                var property = obj.GetType().GetProperty(name);
                if (property != null)
                {
                    objValue = property.GetValue(obj, null);
                }
            }
            return objValue;
        }

        public static object SetValueByKey(this object obj, string name, object value)
        {
            object objValue = null;
            if (obj is Newtonsoft.Json.Linq.JObject)
            {
                var jObject = obj as Newtonsoft.Json.Linq.JObject;
                var property = jObject.Property(name);
                if (property != null)
                {
                    property.Value = JToken.FromObject(value); 
                }
            }
            else
            {
                var property = obj.GetType().GetProperty(name);
                if (property != null)
                {
                    property.SetValue(obj, value, null);
                }
            }
            return objValue;
        }

        public static string GetAppConfig(string keyname)
        {
            var config = System.Configuration.ConfigurationManager.AppSettings[keyname];
            try
            {
                if (string.IsNullOrEmpty(config))
                {
                    string filePath = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Config");
                    TextReader reader = new StreamReader(filePath);
                    XElement xml = XElement.Load(filePath);
                    if (xml != null)
                    {
                        var element = xml.Elements().SingleOrDefault(e => e.Attribute("key") != null && e.Attribute("key").Value.Equals(keyname));
                        if (element != null)
                        {
                            config = element.Attribute("value").Value;
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                config = string.Empty;
            }
            return config;
        }

        public static T ToEnum<T>(this string val)
        {
            return ParseEnum<T>(val);
        }

        public static T ParseEnum<T>(string val)
        {
            try
            {
                return (T)Enum.Parse(typeof(T), val);
            }
            catch (System.Exception)
            {
                return default(T);
            }
        }

        public static string ToJson(this object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }

        public static T ToJsonObject<T>(this string json)
            where T : class
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
            }
            catch (System.Exception)
            {
                return null;
            }

        }

        public static dynamic ToDynamicObject(this string json)
        {
            dynamic dj = null;
            var jsonObj = json.ToJsonObject<JObject>();
            if (jsonObj != null)
            {
                dj = new DynamicJson(jsonObj);
            }
            return dj;
        }

        public static List<dynamic> ToDynamicObjects(this string json)
        {
            List<dynamic> djs = null;
            var jsonObj = json.ToJsonObject<JArray>();
            if (jsonObj != null)
            {
                djs = new List<dynamic>();
                foreach (var j in jsonObj)
                {
                    djs.Add(new DynamicJson(j as JObject));
                }
            }
            return djs;
        }
        public static object ToJsonObject(this string json)
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject(json);
            }
            catch (System.Exception)
            {
                return null;
            }

        }

        public static LambdaExpression GetLambdaExpression(Type type, string propertyName)
        {
            ParameterExpression param = Expression.Parameter(type);
            PropertyInfo property = type.GetProperty(propertyName);
            Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
            var le = Expression.Lambda(propertyAccessExpression, param);
            return le;
        }

        public static IQueryable<TEntity> GetOrderByQueryable<TEntity>(IQueryable<TEntity> query, LambdaExpression orderByExpression, bool asc)
            where TEntity : class
        {
            var orderBy = asc ? "OrderBy" : "OrderByDescending";
            MethodCallExpression orderByCallExpression =
                        Expression.Call(typeof(Queryable),
                        orderBy,
                        new Type[] { typeof(TEntity),
                        orderByExpression.Body.Type},
                        query.Expression,
                        orderByExpression);
            return query.Provider.CreateQuery<TEntity>(orderByCallExpression);
        }


        public static List<QueryParameter> GetQueryParameters(string parameters)
        {
            if (parameters.StartsWith("?"))
            {
                parameters = parameters.Remove(0, 1);
            }

            List<QueryParameter> result = new List<QueryParameter>();

            if (!string.IsNullOrEmpty(parameters))
            {
                string[] p = parameters.Split('&');
                foreach (string s in p)
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        if (s.IndexOf('=') > -1)
                        {
                            string[] temp = s.Split('=');
                            result.Add(new QueryParameter(temp[0], temp[1]));
                        }
                        else
                        {
                            result.Add(new QueryParameter(s, string.Empty));
                        }
                    }
                }
            }

            return result;
        }

        public static string NormalizeRequestParameters(IList<QueryParameter> parameters)
        {
            StringBuilder sb = new StringBuilder();
            QueryParameter p = null;
            for (int i = 0; i < parameters.Count; i++)
            {
                p = parameters[i];
                sb.AppendFormat("{0}={1}", p.Name, p.Value);

                if (i < parameters.Count - 1)
                {
                    sb.Append("&");
                }
            }

            return sb.ToString();
        }

        //加密算法
        public static string Key = "DKMAB5DE";

        public static string MD5Encrypt(string pToEncrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();

        }

        public static string MD5Decrypt(string pToDecrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(Key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.ASCII.GetString(ms.ToArray());

        }


        public static bool IsGuid(string id)
        {
            bool flag = true;
            try
            {
                new Guid(id.Trim());
            }
            catch (Exception)
            {
                flag = false;
            }
            return flag;
        }

        public static string GetLocalResource(string path, string key, string lang)
        {
            object resource = string.Empty;
            if (!string.IsNullOrEmpty(lang))
            {
                resource = HttpContext.GetLocalResourceObject(path, key, new System.Globalization.CultureInfo(lang));
            }
            else
            {
                resource = HttpContext.GetLocalResourceObject(path, key);
            }
            if (resource != null)
            {
                return resource.ToString();
            }
            return string.Empty;
        }

        public static string GetLocalResource(string path, string key)
        {
            return GetLocalResource(path, key, string.Empty);
        }

        public static string GetResource(string key, string lang)
        {
            object resource = string.Empty;
            if (!string.IsNullOrEmpty(lang))
            {
                resource = HttpContext.GetGlobalResourceObject("GlobalResource", key, new System.Globalization.CultureInfo(lang));
            }
            else
            {
                resource = HttpContext.GetGlobalResourceObject("GlobalResource", key);
            }
            if (resource != null)
            {
                return resource.ToString();
            }
            return string.Empty;
        }


        public static string GetResource(string key)
        {
            return GetResource(key, string.Empty);
        }

        public static string StyledSheetEncode(string s)
        {
            s = s.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"").Replace("\r\n", "\\n").Replace("\n\r", "\\n").Replace("\r", "\\n").Replace("\n", "\\n");
            s = s.Replace("/", "\\/");
            return s;
        }

        public static string GetMd5Hash(string input)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        public static void ShowMessage(this Page page, string message, bool close, string redirectUrl)
        {
            string msg = StyledSheetEncode(message);
            string script = @"<script language='javascript'>
    								function AlertMsg()
    								{
    									if(document.readyState=='complete')
    									{
    										alert('{0}');
    										{1}
    									}
    									else
    										setTimeout('AlertMsg()', 100);
    								}
    								AlertMsg();
    							</script>";
            script = script.Replace("{0}", message);
            if (redirectUrl != string.Empty)
            {
                script = script.Replace("{1}", "window.location.href = '" + redirectUrl + "';");
            }
            else
            {
                if (close)
                    script = script.Replace("{1}", "window.close();");
                else
                    script = script.Replace("{1}", string.Empty);
            }
            if (!page.ClientScript.IsStartupScriptRegistered("MsgScript"))
                page.ClientScript.RegisterStartupScript(page.GetType(), "MsgScript", script);
        }

        public static void ShowMessage(this Page page, string message)
        {
            ShowMessage(page, message, false, string.Empty);
        }



        static public string Serialize(object xmlContent, Encoding encoding = null)
        {
            System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(xmlContent.GetType());
            //StringBuilder builder = new System.Text.StringBuilder();
            //StringWriter writer = new StringWriterWithEncoding(Encoding.UTF8);
            //new System.IO.StringWriter(builder);
            //System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(@"c:\test.xml", System.Text.Encoding.UTF8);
            //serializer.Serialize(writer, xmlContent);
            //return builder.ToString();

            MemoryStream stream = new MemoryStream();
            XmlWriterSettings setting = new XmlWriterSettings();
            setting.Encoding = encoding ?? Encoding.UTF8;
            setting.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(stream, setting))
            {
                serializer.Serialize(writer, xmlContent);
            }
            return Encoding.UTF8.GetString(stream.ToArray());
        }

        static public object DeSerialize<XmlType>(string xmlString)
        {

            System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(XmlType));
            StringBuilder builder = new StringBuilder(xmlString);
            System.IO.StringReader reader = new System.IO.StringReader(builder.ToString());
            try
            {
                return serializer.Deserialize(reader);
            }
            catch (Exception)
            {
                return null;
            }
        }

   
        public static string GetSelectLang()
        {
            var langKey = HttpContext.Current.Request.Form.AllKeys.SingleOrDefault(key => key != null && key.Contains("UcLangSelector1$lang"));
            var lang = string.Empty;
            if (!string.IsNullOrEmpty(langKey))
            {
                lang = HttpContext.Current.Request[langKey];
                if (string.IsNullOrEmpty(lang))
                {
                    lang = CookiesHelper.GetCookieValue("lang");
                }
            }
            else
            {
                lang = CookiesHelper.GetCookieValue("lang");
                if (string.IsNullOrEmpty(lang))
                {
                    bool isZH = HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"].StartsWith("zh");
                    if (isZH)
                    {
                        lang = "zh-CN";
                    }
                    else
                    {
                        lang = "en-US";
                    }
                }

            }
            return lang;
        }

        public static void Message(Page page, string p)
        {
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "", string.Format("alert('{0}');", p), true);
        }

        public static void Message(Page page, string message, string url)
        {
            var js = string.Format("window.alert('{0}'); window.location = '{1}';", message, url);
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "", js, true);
        }

        #region 复用部分 Snail

        public static string CreateFlashHtml(string path, string width, string height)
        {
            string html = "";
            html = "<embed src=\"" + path + "\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" name=\"obj1\" width=\"" + width + "\" height=\"" + height + "\" quality=\"High\">";
            return html;
        }

        public static string CreateMusicPlayer(string path, string bgcolor)
        {
            string html = "";
            html += "<object type=\"application/x-shockwave-flash\"";
            html += "data=\"http://www.u-dig.cn/audio/player.swf\"";
            html += "width=\"290\" height=\"24\" id=\"audioplayer2\">";
            html += "<param name=\"movie\" value=\"http://www.u-dig.cn/audio/player.swf\" />";
            html += " <param name=\"wmode\" value=\"opaque\">";
            html += "<param name=\"FlashVars\"";
            html += " value=\"playerID=2&bg=0xffffff&leftbg=0x790853&lefticon=0xffffcc&rightbg=0x790853&rightbghover=0x999999&righticon=0xffffcc&righticonhover=0xffffff&text=0x000000&slider=0xe27ecb&track=0xffffff&border=0xcccccc&loader=0xffd651&";
            html += "soundFile=" + path + "\" />";
            html += "<param name=\"quality\" value=\"high\" />";
            html += "<param name=\"menu\" value=\"false\" />";
            html += "<param name=\"bgcolor\" value=\"" + bgcolor + "\" /></object>";
            return html;
        }

        public static string CreateVideoPlayer(string path, string title, string width, string height)
        {
            string html = "";
            html += "<object type=\"application/x-shockwave-flash\" data=\"vcastr3.swf\" width=\"" + width + "\" height=\"" + height + "\" id=\"vcastr3\">";
            html += "<param name=\"movie\" value=\"vcastr3.swf\"/>";
            html += "<param name=\"allowFullScreen\" value=\"true\" />";
            html += " <param name=\"wmode\" value=\"opaque\">";
            html += "<param name=\"FlashVars\" value=\"xml=";
            html += "    <vcastr>";
            html += "            <channel>";
            html += "            <item>";
            html += "<source>" + path + "</source>";
            html += "<duration></duration>";
            html += "<title>" + title + "</title>";
            html += "<link></link>";
            html += "</item>";
            html += "            </channel>";
            html += "            <config>";
            html += "<bufferTime>4</bufferTime>";
            html += "<contralPanelAlpha>0.75</contralPanelAlpha>";
            html += "<controlPanelBgColor>0x666666</controlPanelBgColor>";
            html += "<controlPanelBtnColor>0xffffff</controlPanelBtnColor>";
            html += "<controlPanelBtnGlowColor>0x00ccff</controlPanelBtnGlowColor>";
            html += "<controlPanelMode>float</controlPanelMode>";
            html += "<defautVolume>0.7</defautVolume>";
            html += "<isAutoPlay>false</isAutoPlay>";
            html += "<isLoadBegin>true</isLoadBegin>";
            html += "<isShowAbout>false</isShowAbout>";
            html += "<scaleMode>showAll</scaleMode>";
            html += "<isRepeat>false</isRepeat>";
            html += "</config>";
            html += "             <plugIns>";
            html += "    <logoPlugIn>";
            html += "            <url>vcastr3_logoPlugIn.swf</url>";
            html += "            <logoText>www.u-dig.cn</logoText>";
            html += "            <logotextalpha>0.75</logotextalpha>";
            html += "            <logotextfontsize>24</logotextfontsize>";
            html += "             <logoTextLink>http://www.u-dig.cn</logoTextLink>";
            html += "            <logotextcolor>0xffffff</logotextcolor>";
            html += "            <textMargin>-5 auto auto 10</textMargin>";
            html += "            <!--logoclipurl></logoclipurl>";
            html += "            <logoclipalpha></logoclipalpha>";
            html += "            <logoClipLink></logoClipLink>";
            html += "            <clipmargin></clipmargin-->";
            html += "    </logoPlugIn>";
            html += "    <!--beginendimageplugin>";
            html += "             <url>vcastr3_beginEndImagePlugIn.swf</url>";
            html += "            <source>temp.swf</source>";
            html += "            <type>end</type>";
            html += "            <scaletype>showAll</scaletype>";
            html += "     </beginendimageplugin-->";
            html += "</plugIns>";
            html += "    </vcastr>\"/>";
            html += "</object>";
            return html;
        }

        public static string ProcessPureText(string original)
        {
            return original.Replace(((char)13).ToString(), "<br>");
        }

        public static string CreateAbstract(string str)
        {
            //str = UbbToHtml(str);
            str = NoHTML(str);
            if (str.Length > 300)
                str = str.Substring(0, 300);
            return str;
        }

        public static string CreateAbstract(string str, int num)
        {
            //str = UbbToHtml(str);
            str = NoHTML(str);
            if (str.Length > num)
                str = str.Substring(0, num) + "...";
            return str;
        }

        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;
        }

        private static bool IsEnglishCharacter(String strin)
        {
            char c;
            for (int i = 0; i < strin.Length; i++)
            {
                c = char.Parse(strin.Substring(i, 1));
                if ((c <= 0x007A && c >= 0x0061) == false &&
                   (c <= 0x005A && c >= 0x0041) == false)
                    return false;
            }
            return true;

        }

        private static bool HaveChineseCode(string testString)
        {
            if (Regex.IsMatch(testString, @"[\u4e00-\u9fa5]+"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private static string GetPYChar(string c)
        {
            byte[] array = new byte[2];
            array = System.Text.Encoding.Default.GetBytes(c);
            int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
            if (i < 0xB0A1) return "*";
            if (i < 0xB0C5) return "a";
            if (i < 0xB2C1) return "b";
            if (i < 0xB4EE) return "c";
            if (i < 0xB6EA) return "d";
            if (i < 0xB7A2) return "e";
            if (i < 0xB8C1) return "f";
            if (i < 0xB9FE) return "g";
            if (i < 0xBBF7) return "h";
            if (i < 0xBFA6) return "g";
            if (i < 0xC0AC) return "k";
            if (i < 0xC2E8) return "l";
            if (i < 0xC4C3) return "m";
            if (i < 0xC5B6) return "n";
            if (i < 0xC5BE) return "o";
            if (i < 0xC6DA) return "p";
            if (i < 0xC8BB) return "q";
            if (i < 0xC8F6) return "r";
            if (i < 0xCBFA) return "s";
            if (i < 0xCDDA) return "t";
            if (i < 0xCEF4) return "w";
            if (i < 0xD1B9) return "x";
            if (i < 0xD4D1) return "y";
            if (i < 0xD7FA) return "z";
            return "*";
        }

        public static string GetIndexChar(string original)
        {
            if (HaveChineseCode(original.Substring(0, 1)))
            {
                return GetPYChar(original);
            }
            else if (IsEnglishCharacter(original.Substring(0, 1)))
            {
                return original.Substring(0, 1).ToLower();
            }
            else
            {
                return "#";
            }
        }

        #endregion


        public static T GetAppConfig<T>(string key)
        {
            T val = default(T);
            try
            {
                var value = GetAppConfig(key);
                if (typeof(T).IsEquivalentTo(typeof(Guid)))
                {
                    val = (T)Convert.ChangeType(new Guid(value), typeof(T));
                }
                else
                {
                    val = (T)Convert.ChangeType(value, typeof(T));
                }
                
            }
            catch(Exception)
            {

            }
            return val;
        }
    }
}
